package com.timesheet.server.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.timesheet.server.common.models.EffortTrackerDTO;
import com.timesheet.server.core.mapper.Mapper3;
import com.timesheet.server.core.models.EffortTracker;
import com.timesheet.server.core.util.HibernateUtil;
import com.timesheet.server.core.util.PMManager;

public class UtilisationDao {

	public List<EffortTrackerDTO> geUtilisation(String projId) {
		List<EffortTrackerDTO> effortTrackerDTOsList = null;
		List list = PMManager.getUtilisation(projId);
		// if(list!=null && list.size()==4){
		effortTrackerDTOsList = new ArrayList<EffortTrackerDTO>();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			EffortTrackerDTO dto = new EffortTrackerDTO();
			dto.setId(new Long(obj[0].toString()));
			dto.setProjectId(obj[1].toString());
			dto.setHours(new Double(obj[2].toString()));
			effortTrackerDTOsList.add(dto);
		}

		// }
		return effortTrackerDTOsList;
	}

	public List<EffortTrackerDTO> getUtilisationBasedOnTheProjects(String[] projects) {
		if (projects == null & projects.length == 0) {
			return Collections.emptyList();
		}
		List<EffortTracker> list = new ArrayList<EffortTracker>();
		HibernateUtil hibenateUtil = new HibernateUtil();
		Session session = hibenateUtil.getSession();
		for (String string : projects) {
			String sql = "SELECT * FROM EffortTracker eff where eff.projectId='"
					+ string + "' GROUP BY eff.projectId";
			SQLQuery query = session.createSQLQuery(sql);
			query.addEntity(EffortTracker.class);
			list.addAll(query.list());
		}
		
		List<EffortTrackerDTO> dtoList = convertEffortTrackerList2EffortDtoList(list);		
		return dtoList;

	}
	
	
	
	private List<EffortTrackerDTO> convertEffortTrackerList2EffortDtoList(List<EffortTracker> list){
		List<EffortTrackerDTO> effortDtoList = new ArrayList<EffortTrackerDTO>();
		for (EffortTracker effortTracker : list) {
			effortDtoList.add(Mapper3.map(new EffortTrackerDTO(), effortTracker));
		}
		return effortDtoList ;
				
	}

}
